"""
时间线模块 - 处理历史时间线展示功能
"""

import streamlit as st
import pandas as pd
import plotly.express as px

@st.cache_data
def get_chinese_dynasties():
    """获取中国朝代数据"""
    dynasties = [
        {"name": "夏朝", "start": -2100, "end": -1600, "color": "#FFD700"},
        {"name": "商朝", "start": -1600, "end": -1046, "color": "#FFA500"},
        {"name": "周朝", "start": -1046, "end": -256, "color": "#FF8C00"},
        {"name": "秦朝", "start": -221, "end": -206, "color": "#FF7F50"},
        {"name": "汉朝", "start": -202, "end": 220, "color": "#FF6347"},
        {"name": "三国", "start": 220, "end": 280, "color": "#FF4500"},
        {"name": "晋朝", "start": 266, "end": 420, "color": "#FF0000"},
        {"name": "南北朝", "start": 420, "end": 589, "color": "#DC143C"},
        {"name": "隋朝", "start": 581, "end": 618, "color": "#B22222"},
        {"name": "唐朝", "start": 618, "end": 907, "color": "#8B0000"},
        {"name": "五代十国", "start": 907, "end": 979, "color": "#800000"},
        {"name": "宋朝", "start": 960, "end": 1279, "color": "#8B4513"},
        {"name": "元朝", "start": 1271, "end": 1368, "color": "#A0522D"},
        {"name": "明朝", "start": 1368, "end": 1644, "color": "#D2691E"},
        {"name": "清朝", "start": 1644, "end": 1912, "color": "#CD853F"}
    ]
    return dynasties

@st.cache_data
def get_artifact_dynasty_mapping():
    """获取文物与朝代的对应关系"""
    mapping = {
        "青铜器": ["商朝", "周朝"],
        "兵马俑": ["秦朝"],
        "敦煌壁画": ["唐朝", "宋朝", "元朝"],
        "唐三彩": ["唐朝"],
        "越王勾践剑": ["周朝"],
        "甲骨文": ["商朝"],
        "四羊方尊": ["商朝"],
        "汉长信宫灯": ["汉朝"],
        "曾侯乙编钟": ["周朝"],
        "清明上河图": ["宋朝"]
    }
    return mapping

def create_timeline_chart(artifact_name=None):
    """创建中国朝代时间线图表"""
    dynasties = get_chinese_dynasties()
    
    timeline_data = []
    for dynasty in dynasties:
        duration = dynasty["end"] - dynasty["start"]
        
        opacity = 0.7
        if artifact_name:
            mapping = get_artifact_dynasty_mapping()
            if artifact_name in mapping and dynasty["name"] in mapping[artifact_name]:
                opacity = 1.0  
        
        timeline_data.append({
            "朝代": dynasty["name"],
            "开始年份": dynasty["start"],
            "结束年份": dynasty["end"],
            "持续时间": duration,
            "颜色": dynasty["color"],
            "透明度": opacity
        })
    
    df = pd.DataFrame(timeline_data)
    
    df["排序"] = df["开始年份"]
    
    df["显示开始"] = df["开始年份"].apply(lambda x: f"{abs(x)}BC" if x < 0 else f"{x}AD")
    df["显示结束"] = df["结束年份"].apply(lambda x: f"{abs(x)}BC" if x < 0 else f"{x}AD")
    df["时期"] = df.apply(lambda x: f"{x['显示开始']} - {x['显示结束']}", axis=1)
    
    fig = px.timeline(
        df.sort_values("排序"), 
        x_start="开始年份", 
        x_end="结束年份", 
        y="朝代",
        color="朝代",
        hover_data=["时期", "持续时间"],
        color_discrete_map={row["朝代"]: row["颜色"] for _, row in df.iterrows()},
        opacity=[row["透明度"] for _, row in df.iterrows()]
    )
    
    fig.update_layout(
        title={
            "text": f"中国历史朝代时间线{' - ' + artifact_name if artifact_name else ''}",
            "font": {"family": "Source Han Serif CN, Microsoft YaHei, SimHei, sans-serif", "size": 18, "color": "#8C3D2B"}
        },
        xaxis=dict(
            title="年份",
            tickvals=[-2000, -1500, -1000, -500, 0, 500, 1000, 1500, 2000],
            ticktext=["2000BC", "1500BC", "1000BC", "500BC", "0", "500AD", "1000AD", "1500AD", "2000AD"],
            showgrid=True,
            gridcolor="rgba(200,200,200,0.2)"
        ),
        yaxis=dict(
            title="",
            autorange="reversed"
        ),
        height=400,
        plot_bgcolor="white",
        paper_bgcolor="white",
        font=dict(family="Source Han Serif CN, Microsoft YaHei, SimHei, sans-serif"),
        margin=dict(l=50, r=50, t=60, b=50),
        showlegend=False
    )
    
    if artifact_name:
        mapping = get_artifact_dynasty_mapping()
        if artifact_name in mapping:
            for dynasty_name in mapping[artifact_name]:
                dynasty = next((d for d in dynasties if d["name"] == dynasty_name), None)
                if dynasty:
                    mid_year = (dynasty["start"] + dynasty["end"]) / 2
                    fig.add_annotation(
                        x=mid_year,
                        y=dynasty_name,
                        text=f"《{artifact_name}》",
                        showarrow=True,
                        arrowhead=2,
                        arrowcolor="#8C3D2B",
                        arrowsize=1,
                        arrowwidth=2,
                        bgcolor="rgba(255,255,255,0.9)",
                        bordercolor="#8C3D2B",
                        borderwidth=1,
                        borderpad=4,
                        font=dict(family="Source Han Serif CN, Microsoft YaHei, SimHei, sans-serif", color="#8C3D2B", size=12, weight="bold")
                    )
    
    return fig 